package com.panopset;

import java.io.File;
import java.io.StringWriter;

import com.panopset.compat.Logz;
import com.panopset.compat.Strings;
import com.panopset.io.Filez;
import com.panopset.io.ShortFile;

/**
 *
 * Creates cp.props file which has CP property set to the classpath of the
 * current project pom.xml.
 * 
 * Useful in ant scripts.
 * 
 * @author Karl Dinwiddie
 * 
 */
public final class Pom2classpathProps {

	private final Filez fz = new Filez();
	private final File pomDir;

	/**
	 * @param args
	 *            args[0] = pom directory. args[1] = local maven repository
	 *            directory. Usually ${user.home}/.m2/repository
	 * @throws Exception
	 *             Exception.
	 */
	public static void main(final String[] args) throws Exception {
		if (args == null || args.length != 2) {
			printUsage();
			return;
		}
		new Pom2classpathProps(args[0], args[1]).go();
	}

	/**
	 * Go.
	 * 
	 * @throws Exception
	 *             Exception.
	 */
	private void go() throws Exception {
		final StringWriter sw = new StringWriter();
		boolean firstTime = true;
		for (MavenAuditor.MavenDependency d : new MavenAuditor()
				.loadPomDependencies(new File(new Filez().combinePaths(pomDir,
						PomParser.POM_FILE)))) {
			if (d.getScope().trim().equalsIgnoreCase("test")) {
				continue;
			}
			if (firstTime) {
				firstTime = false;
			} else {
				sw.append(";");
			}
			sw.append(d.getLocalRepositoryJar());
		}
		String rtn = sw.toString().replace("\\", "/");
		File f = new File("cp.props");
		if (!new ShortFile().saveStringToFile("CP=" + rtn, f)) {
			Logz.log("Error writing to " + fz.getCanonicalPath(f));
		}
	}

	private Pom2classpathProps(final String pomDirectoryPath,
			final String localMavenRepo) {
		MavenAuditor.setMavenHome(localMavenRepo);
		pomDir = new File(pomDirectoryPath);
	}

	private static void printUsage() {
		System.out.println(getUsageMessage());
	}

	private static String getUsageMessage() {
		String eol = new Strings().getEol();
		StringWriter sw = new StringWriter();
		sw.append("Usage:");
		sw.append(eol);
		sw.append("java Pom2classpathProps pomDir mavenRepoDir");
		sw.append(eol);
		sw.append(" where pomDir is the maven project directory,");
		sw.append(eol);
		sw.append(" mavenRepoDir is the maven repository home:");
		sw.append(" usually ${user.home}/.m2");
		sw.append(eol);
		return sw.toString();
	}

}
